package cn.edu.buu.news.service.impl;

import cn.edu.buu.news.entity.Tool;
import cn.edu.buu.news.mapper.ToolMapper;
import cn.edu.buu.news.service.ToolService;
import cn.edu.buu.news.vo.PageQuery;
import cn.edu.buu.news.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ToolServiceImpl implements ToolService {

    @Autowired
    private ToolMapper toolMapper;

    @Override
    public void add(Tool tool) {
        toolMapper.insert(tool);
    }

    @Override
    public void deleteById(Long id) {
        toolMapper.deleteById(id);
    }

    @Override
    public void update(Tool tool) {
        toolMapper.update(tool);
    }

    @Override
    @Transactional(readOnly = true)
    public Tool findById(Long id) {
        return toolMapper.selectById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Tool> findAll() {
        return toolMapper.selectAll();
    }

    @Override
    @Transactional(readOnly = true)
    public PageResult<Tool> findByPage(PageQuery query) {
        // 校验分页参数
        int page = query.getPage() < 1 ? 1 : query.getPage();
        int size = query.getSize() < 1 ? 10 : query.getSize();
        int offset = (page - 1) * size;

        List<Tool> list = toolMapper.selectByPage(query, offset);
        Long total = toolMapper.selectCount(query);
        return new PageResult<>(list, total);
    }
}